package com.info33.platform.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.info33.platform.common.constant.TableConstant;
import com.info33.platform.common.exception.TransactionalException;
import com.info33.platform.common.mvc.vo.Result;
import com.info33.platform.system.dao.SysDeptDao;
import com.info33.platform.system.dao.SysDeptPostDao;
import com.info33.platform.system.dto.SysDeptDTO;
import com.info33.platform.system.entity.SysDept;
import com.info33.platform.system.entity.SysDeptPost;
import com.info33.platform.system.service.SysDeptService;
import com.info33.platform.system.util.enums.DeptTypeEnum;
import com.info33.platform.system.vo.SysDeptVO;
import com.info33.platform.system.vo.SysUserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author admin
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptDao, SysDept> implements SysDeptService {

    @Autowired
    private SysDeptDao sysDeptDao;
    @Autowired
    private SysDeptPostDao sysDeptPostDao;

    /**
     * 部门树结构递归
     *
     * @param sysDeptVOList -
     * @param pid           -
     * @return -
     */
    public List<SysDeptVO> deptTree(List<SysDeptVO> sysDeptVOList, Long pid) {
        List<SysDeptVO> collect = sysDeptVOList.stream().filter(l -> l.getPid().equals(pid)).collect(Collectors.toList());
        collect.forEach(l -> l.setSysDeptVOList(deptTree(sysDeptVOList, l.getId())));
        return collect;
    }

    @Override
    public Result<Object> pcRemove(Long id) {
        if (sysDeptDao.selectCount(new QueryWrapper<SysDept>().eq(TableConstant.PID, id)) > 0) {
            return Result.error("存在下级部门，不允许删除");
        }
        if (sysDeptPostDao.selectCount(new QueryWrapper<SysDeptPost>().eq("dept_id", id)) > 0) {
            return Result.error("部门存在用户，不允许删除");
        }
        return sysDeptDao.deleteById(id) > 0 ? Result.ok() : Result.error();
    }

    @Override
    public Result<SysDeptVO> pcTree(SysDeptDTO dto, SysUserVO currentUser) {
        SysDeptVO vo = new SysDeptVO();
        LambdaQueryWrapper<SysDept> qw = new LambdaQueryWrapper<SysDept>()
                .eq(SysDept::getTenantId, currentUser.getSysTenantUserVO().getTenantId());
        if (ObjectUtils.isEmpty(dto.getId())) {
            qw.eq(SysDept::getPid, 0L);
        } else {
            qw.eq(SysDept::getId, dto.getId());
        }
        qw.last(TableConstant.LIMIT_ONE);
        SysDept entity = sysDeptDao.selectOne(qw);
        if (ObjectUtils.isEmpty(entity)) {
            return Result.error("您目前账号不存在部门信息");
        }
        BeanUtils.copyProperties(entity, vo);
        vo.setSysDeptVOList(deptTree(sysDeptDao.noTopList(currentUser),
                ObjectUtils.isEmpty(dto.getId()) ? entity.getId() : dto.getId()));
        return Result.ok(vo);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Long createDept(String name, Long userId, SysUserVO currentUser) {
        SysDept company = sysDeptDao.selectOne(new QueryWrapper<SysDept>()
                .eq("type", DeptTypeEnum.COMPANY)
                .eq(TableConstant.TENANT_ID, currentUser.getTenant().getId())
                .last(TableConstant.LIMIT_ONE));
        SysDept sd = new SysDept();
        sd.setName(name);
        sd.setPid(company.getId());
        sd.setType(DeptTypeEnum.DEPARTMENT);
        sd.setDeptLevel(2);
        sd.setDeptDesc("该主体所拥有的部门");
        if (sysDeptDao.insert(sd) != 1) {
            throw new TransactionalException();
        }
        return sd.getId();
    }

}